<?php


namespace app\app\controller;


use app\model\AppUserWallet;
use app\model\AppWithdrawals;
use app\util\ReturnCode;
use think\Db;
use think\Exception;
use think\exception\DbException;

class Withdrawals extends Base
{
    //获取可提现的总额
    public function getWithdrawals()
    {
        $uid = $this->userInfo['uid'];
        $where = ['uid' => $uid];
        $where = $this->addTid($where);
        $model = AppUserWallet::get($where);
        $data = $model->getData();
        return $this->buildSuccess($data);
    }

    //申请提现
    public function apply()
    {
        $wxNo = $this->request->get('wx_no');
        //现在默认都是全金额提现
        $uid = $this->userInfo['uid'];
        $where = ['uid' => $uid];
        $where = $this->addTid($where);
        $model = AppUserWallet::get($where);
        if ($model->income < 100) {
            return $this->buildFailed(ReturnCode::FAILED, '提现最少1元起');
        }
        $data = ['uid' => $uid, 'money' => $model->income,'wx_no'=>$wxNo];
        $data = $this->addTid($data);
        Db::startTrans();
//        try {
            $done = AppWithdrawals::create($data);
            if ($done) {
                $model->setAttr('income', 0);
                $done = $model->allowField(true)->save();
                if (!$done) {
                    throw new Exception();
                }
            } else {
                throw new Exception();
            }
            Db::commit();
            return $this->buildSuccess(null);
//        } catch (Exception $e) {
//            Db::rollback();
//        }
        return $this->buildFailed(ReturnCode::FAILED, '操作失败');

    }

    //获取提现记录
    public function geRecord()
    {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $where = [];
        $where = $this->addTid($where);
        $where['uid'] = $this->userInfo['uid'];
        $obj = new AppWithdrawals();
        try {
            $listObj = $obj->where($where)->order('create_time DESC')->paginate($limit, false, ['page' => $start])->toArray();
            return $this->buildSuccess([
                'list' => $listObj['data'],
                'count' => $listObj['total']
            ]);
        } catch (DbException $e) {
        }
        return $this->buildFailed(ReturnCode::FAILED, '获取失败');
    }
}